package com.ludomancy.timescape;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

import com.ludomancy.gamelib.Widget;

public class SliderWidget extends Widget
{
	private int maxValue;
	private int currentValue;
	private SliderListener listener;
	private static final int SLIDER_WIDTH = 12;
	private int realWidth;
	
	public interface SliderListener
	{
		void onValueChanged(int newValue);
	}

	public SliderWidget(Widget parent, Rectangle area, SliderListener listener, int maxValue, int realWidth)
	{
		super(parent, area);
		this.maxValue = maxValue;
		this.listener = listener;
		this.realWidth = realWidth;
	}

	public void paint(Graphics g)
	{
		int halfY = getHeight()/2;
		g.setColor(Color.GRAY);
		int gap = getWidth()-realWidth;
		g.drawLine(gap/2, halfY, getWidth()-gap/2, halfY);
		// paint marker
		int markerX =(int)( (currentValue * (double)realWidth)/maxValue);
		g.fill3DRect(markerX-SLIDER_WIDTH/2 + gap/2, halfY-SLIDER_WIDTH/2, SLIDER_WIDTH, SLIDER_WIDTH, true);
	}

	public void mouseDown(Point pos)
	{
		int sectionWidth = Math.max(1, realWidth/maxValue);
		int gap = getWidth()-realWidth;
		// clamp position
		int realX = pos.x - gap/2;
		realX = Math.max(0, realX);
		realX = Math.min(realWidth, realX);
		currentValue = realX / sectionWidth;
		
		// clamp values
		currentValue = Math.max(0, currentValue);
		currentValue = Math.min(maxValue, currentValue);
		if(listener != null)
		{
			listener.onValueChanged(currentValue);
		}
	}
}
